using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class MaterialFlipper : KnowsWhenSeen
{
	public FlickerMaterialStep[] m_FlickerMatSteps;
	public int m_EffectsWhichMatSlot = 0;

	private int m_currStepIdx = -1;
	private int m_matId;
	private float m_currCountdown = 0.01f;

	void Start()
	{
	}

	void Update()
	{
		if ( m_currCountdown > 0 )
		{
			m_currCountdown -= Time.deltaTime;
			if ( m_currCountdown <= 0f )
			{
				if ( m_FlickerMatSteps.Length > 0 )
				{
					m_currStepIdx++;
					if ( m_currStepIdx > m_FlickerMatSteps.Length - 1 )
					{
						m_currStepIdx = 0;
					}

					SetMat( m_FlickerMatSteps[ m_currStepIdx ].m_Mat );
					m_currCountdown = m_FlickerMatSteps[ m_currStepIdx ].m_Seconds;
				}
			}
		}
	}

	void SetMat( Material matToSet )
	{
		if ( renderer != null )
		{
			if ( renderer.materials != null )
			{
				if ( m_EffectsWhichMatSlot < renderer.materials.Length ) // not past end
				{
					// Make a copy of mat array
					Material[] copysMats = new Material[renderer.materials.Length];
					for(int i=0; i<copysMats.Length;i++)
					{
						if ( i == m_EffectsWhichMatSlot )
						{
							copysMats[i] = matToSet; // <<<<<<<<<<<< Finally, we get to set it !!!!
						}
						else // just copy the one that was there
						{
							copysMats[i] = renderer.materials[i];
						}
					}
					renderer.materials = copysMats;
				}
			}
		}
	}

}

[System.Serializable]
public class FlickerMaterialStep
{
	public Material m_Mat;
	public float m_Seconds = 0.5f;
}